package com.cn.ysf.newbeemall.controller.admin;

import com.cn.ysf.newbeemall.pojo.AdminUser;
import com.cn.ysf.newbeemall.service.AdminUserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author ysf
 * @date 2019/12/12 10:53
 */
@Controller
@RequestMapping("admin")
public class LoginController {

    @Resource
    private AdminUserService adminUserService;
    /**
     * 跳转后台登陆页面
     * @return
     */
    @GetMapping("login")
    public String login(){
        return "admin/login";
    }
    /**
     * 跳转后台主页面
     * @return
     */
    @PostMapping("login")
    public String index(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession session){
        AdminUser adminUser=adminUserService.login(userName, password);
        if(adminUser==null){
            session.setAttribute("errorMsg", "登陆失败，请联系作者获得测试账号");
            return "admin/login";
        }
        //从session中获取验证码
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            session.setAttribute("errorMsg", "验证码错误");
            return "admin/login";
        }
        session.setAttribute("loginUser", adminUser.getLoginUserName());
        session.setAttribute("loginUserId", adminUser.getAdminUserId());
        return "redirect:/admin/index";
    }

    @GetMapping("index")
    public String toindex(HttpServletRequest request){
        request.setAttribute("path", "index");
        return "admin/index";
    }

}
